import React, { PropTypes, PureComponent } from 'react';
import { connect } from 'dva';
import { QuestionCircleOutlined } from '@ant-design/icons';
import { Form } from '@ant-design/compatible';
import '@ant-design/compatible/assets/index.css';
import { message, Tooltip } from 'antd';
import { TableC, PrimaryGhostC } from '../../comps';
import config from '../../comps/business/tradingMarket/config';
import style from './index.less';
import { fixedNum } from '../../utils/utils';
@Form.create()
class TrialResult extends PureComponent {
  state = {
    dataSource: [],
    columns: [],
  };

  componentDidMount() {
    this.props.onRef(this);
  }

  componentWillUnmount() {
    this.setState = (state, callback) => {
      return;
    };
  }

  //刷新列表
  refreshClick = () => {
    const { dataObj } = this.props;
    if (dataObj.isReset) {
      //判断是否点击了重置 点击页码不进行后台查询
      message.warning('您已重置查询字段，请设置条件后执行查询');
      return;
    }
    //无查询条件跳出
    if (!(dataObj.productGroup || dataObj.product.length > 0) || !dataObj.template) {
      message.warning('请设置条件后执行查询');
      return;
    }
    this.getResultList();
  };

  //获取表格数据
  getResultList = () => {
    const { dataObj } = this.props;
    this.props.dispatch({
      type: 'portfolioTrialM/getPortfolioList',
      payload: {
        groupId: dataObj.productGroup,
        portfolioCodes: dataObj.product.length > 0 ? dataObj.product : undefined,
      },
      callback: (data) => {
        if (data && data.columns && data.columns.length) {
          //判断是否是持仓（持仓不需要children
          data.dataSource.map((item) => {
            if (item.stockCode) return;
            item.children = [];
          });
          this.setState({
            columns: data.columns,
            dataSource: data.dataSource,
          });
        } else {
          this.setState({
            dataSource: [],
            columns: [],
          });
        }
      },
    });
  };

  //表格行扩展
  onExpandChange = (expanded, record) => {
    const { dataObj } = this.props;
    if (dataObj.isReset) {
      //判断是否点击了重置 点击页码不进行后台查询
      message.warning('您已重置查询字段，请设置条件后执行查询');
      return;
    }
    if (!expanded || record.children.length > 0) return;
    this.selectPortfolioList(record);
  };

  //插入children
  setDataList = (id, data, list) => {
    let listItem = [...list];
    let arr = [];
    if (listItem.length > 0) {
      arr = listItem.filter((item) => {
        return item.id == id;
      });
    }
    if (arr.length > 0) {
      listItem.map((item) => {
        if (id == item.id) {
          item.children = data;
        }
      });
    } else {
      listItem.map((item) => {
        if (item.stockCode) return;
        item.children = this.setDataList(id, data, item.children);
      });
    }
    return listItem;
  };

  //获取表格数据
  selectPortfolioList = (value) => {
    this.props.dispatch({
      type: 'portfolioTrialM/selectPortfolioList',
      payload: {
        groupId: value.openType != 1 ? '' : value.portfolioCode,
        portfolioCode: value.openType != 1 ? value.portfolioCode : undefined,
        totalMarketValue: value.marketValue,
        adjustedTotalMarketValue: value.adjustedMarketValue,
      },
      callback: (data) => {
        if (data && data.dataSource.length) {
          //判断是否是持仓（持仓不需要children
          data.dataSource.map((item) => {
            if (item.stockCode) return;
            item.children = [];
          });
          let dataList = this.setDataList(value.id, data.dataSource, this.state.dataSource);
          this.setState({
            dataSource: dataList,
          });
        }
      },
    });
  };

  //改变表格列
  changeColumns = (columns) => {
    const arr = columns;
    let arrList = [...arr].splice(0, 8);
    if (arr && arr.length) {
      arr.map((item) => {
        if (item.key == 'stockCode') {
          item.render = (text, record) => {
            // XN开头为虚拟
            if (record.stockCode && record.stockCode.indexOf('XN') === 0) {
              return (
                <>
                  {text}{' '}
                  <Tooltip title={`虚拟债券标的`}>
                    <QuestionCircleOutlined />
                  </Tooltip>
                </>
              );
            }
            return text;
          };
        }
        if (item.key == 'stockName') {
          item.render = (text, record) => {
            if (record.stockCode && record.stockCode.indexOf('XN') === 0) {
              const tradeInfo = record.tradeInfo ? JSON.parse(record.tradeInfo) : {};
              const getTradingNameTips = () => {
                const { timeLimit, subjectrating, bondrating, bondType } = tradeInfo;
                return (
                  <div>
                    <span>{timeLimit && `期限：${timeLimit}`}</span> <span>{subjectrating && `主体评级：${subjectrating}`}</span>{' '}
                    <span>{bondrating && `债项评级：${bondrating === 'NOT_RATED' ? '无评级' : bondrating}`}</span> <span>{bondType && `债券类型：${bondType}`}</span>
                  </div>
                );
              };
              return (
                <>
                  {text}{' '}
                  <Tooltip title={getTradingNameTips()}>
                    <QuestionCircleOutlined />
                  </Tooltip>
                </>
              );
            }
            return text;
          };
        }
        if (item.key == 'exchangeCode') {
          item.render = (text, record) => {
            let findvalue = config.filter((item) => {
              return text == item.value;
            });
            if (findvalue && findvalue.length > 0) {
              return findvalue[0].title;
            } else {
              return '--';
            }
          };
        } else if (item.key == 'amount') {
          item.align = 'right';
          item.render = (text, record) => {
            let value = parseInt(record.adjustedAmount) - parseInt(record.amount);
            return (
              <span>
                {!text && text != 0 ? '--' : text}
                {(text || text == 0) && value !== 0 ? (
                  <span className={value > 0 ? style.plus : style.reduce}>
                    {value > 0 ? '+' : '-'}
                    {Math.abs(value)}
                  </span>
                ) : null}
              </span>
            );
          };
        } else if (item.key == 'adjustedMarketValue' || item.key == 'marketValue' || item.key == 'costPrice' || item.key == 'price') {
          item.align = 'right';
          item.render = (text, record) => {
            // 虚拟标默认100
            if (item.key == 'price' && record.stockCode && record.stockCode.indexOf('XN') === 0) {
              return fixedNum(100, 4);
            }
            return text ? fixedNum(text * 1, 4) : '--';
          };
        }
        if (item.key == 'adjustedYield' || item.key == 'yield' || item.key == 'weight' || item.key == 'adjustedWeight') {
          item.align = 'right';
          item.width = 80;
          item.render = (text, record) => {
            return text !== null ? parseFloat(text * 100).toFixed(2) + '%' : '--';
          };
        }
        if (item.key == 'adjustedMarketValue' || item.key == 'marketValue') {
          item.width = 140;
        }
        if (item.key == 'assetType' || item.key == 'exchangeCode') {
          item.width = 80;
        }
      });

      let obj1 = {
        dataIndex: 'adjustBefore',
        key: 'adjustBefore',
        title: '调整前',
        children: [],
      };
      let obj2 = {
        dataIndex: 'adjustAfter',
        key: 'adjustAfter',
        title: '调整后',
        align: 'center',
        children: [],
      };
      arr.map((item) => {
        if (item.key == 'marketValue' || item.key == 'weight' || item.key == 'yield') {
          obj1.children.push(item);
        } else if (item.key == 'adjustedMarketValue' || item.key == 'adjustedWeight' || item.key == 'adjustedYield') {
          obj2.children.push(item);
        }
      });
      arrList.push(obj1, obj2);
    }

    return arrList;
  };

  render() {
    const { columns, dataSource } = this.state;
    const { loading } = this.props;
    const newColumns = this.changeColumns(columns);
    return (
      <div className={style.trialResult}>
        <div className={style.refreshBtn}>
          <PrimaryGhostC title='刷新' onClick={() => this.refreshClick()} />
        </div>
        <div style={{ clear: 'both' }}></div>
        <TableC
          columns={newColumns}
          dataSource={dataSource}
          selfScrollY={true}
          rowKey='id'
          hidePage={true}
          loading={loading.effects['portfolioTrialM/getPortfolioList'] === true || loading.effects['portfolioTrialM/selectPortfolioList'] === true}
          onExpand={(expanded, record) => this.onExpandChange(expanded, record)} //点击行展开事件
        />
      </div>
    );
  }
}
export default connect(({ portfolioTrialM, loading }) => ({ portfolioTrialM, loading: loading }))(TrialResult);
